package com.ivr.cm.handler.impl;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;

import com.ivr.cm.data.BaseData;
import com.ivr.cm.data.ValidateData;
import com.ivr.cm.handler.BaseHandler;
import com.ivr.cm.handler.validate.ValidateServiceIF;
import com.ivr.cm.service.impl.DbService;
import com.ivr.cm.service.impl.FilterServiceImpl;
import com.ivr.cm.util.SpringServiceUtil;
import com.ivr.cm.vo.UserCallinVo;

public class CommonValidateHandler extends BaseHandler {
	private static Logger logger = Logger.getLogger(CommonValidateHandler.class);
	/**定义鉴权请求包VO*/
	private ValidateData validateData;
	
	@Override
	protected String action(BaseData baseData) {
		logger.info(String.format("[%s][%s]业务鉴权开始", baseData.getCalling(), baseData.getLong_called()));
		validateData = new ValidateData();
		validateData.setBaseData(baseData);
		
		/**开始鉴权接口业务处理   使用链处理方式*/
		ValidateServiceIF validateChain = (ValidateServiceIF) SpringServiceUtil.getService("validateChain");
		validateChain.doProcess(validateData);
		
		/**获得验证结果并拼装返回 格式按照高阳要求的格式进行拼接*/
		String result = validateData.getResult()+"|"+validateData.getVoice()+"|"+validateData.getTimeRemain()+"|"+validateData.getHungupSms();
		logger.info(String.format("[%s][%s]鉴权返回:%s", baseData.getCalling(), baseData.getLong_called(), result));
		
		/**判断呼入入库*/
		if(validateData.getResult() != 0 && validateData.getResult() != 1){
			/**验证不通过  不进行过滤处理*/
			insertCallin(baseData,0);
		}else{
			/**验证通过 进行计算是否进行过滤*/
			insertCallin(baseData,1);
		}
		return result;
	}
	
	/**
	 * 呼入入库
	 * @param baseData
	 * @param isflter
	 */
	private void insertCallin(BaseData baseData,int isflter){
		try{
			
			/**设置呼入记录对象*/
			UserCallinVo userCallinVo = new UserCallinVo();
			userCallinVo.setMobile(baseData.getCalling());
			userCallinVo.setSp_number(baseData.getLong_called());
			userCallinVo.setProvince(baseData.getProvince());
			userCallinVo.setCity(baseData.getCity());
			userCallinVo.setState_code(validateData.getStatecode());
			userCallinVo.setLinkId(baseData.getLinkId());
			
			/**根据标志判断是否进行过滤    0  不过滤   1 过滤*/
			if(isflter == 1){
				/**当进行过滤时对用户进行过滤算法 算出是否进行过滤, 如果被过滤把过滤放入过滤缓存中*/
				userCallinVo.setIsfilter(FilterServiceImpl.callinFilter(baseData));
			}else {
				userCallinVo.setIsfilter(0);
			}
			String[] tmp = baseData.getBody().split("\\|");
			String areacode = "";
			if(tmp.length >= 4){
				areacode = tmp[3];
			}
			userCallinVo.setArea_code(areacode);
			
			/**数据库服务 ，实现了异步入库*/
			DbService dbService = (DbService) SpringServiceUtil.getService("dbService");
			dbService.doProcess(userCallinVo);
		}catch (Exception e) {
			logger.error(String.format("鉴权入库异常:%s", ExceptionUtils.getFullStackTrace(e)));
		}
	}
}
